package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyComment;
import cn.wolfcode.trip.base.domain.Tag;
import cn.wolfcode.trip.base.mapper.StrategyCommentMapper;
import cn.wolfcode.trip.base.mapper.TagMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyCommentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentMapper strategyCommentMapper;
    @Autowired
    private TagMapper tagMapper;

    /**
     * 1.根据攻略id分页查询其下的评论
     *
     * @param qo
     * @return
     */
    public PageInfo<?> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(),qo.getOrderBy());
        List<StrategyComment> list = strategyCommentMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    /**
     * 2.保存用户提交的攻略评论
     *
     * @param strategyComment
     */
    public Long save(StrategyComment strategyComment, String[] tags) {
        /*在业务层设置攻略评论的创建时间*/
        strategyComment.setCreateTime(new Date());
        strategyCommentMapper.insert(strategyComment);
        /*获得新插入的主键自增长的id*/
        Long strategyCommentId = strategyComment.getId();
        if (tags != null && tags.length > 0) {
            Tag temp = new Tag();
            temp.setState(0);
            for (String tag : tags) {
                temp.setName(tag);
                tagMapper.insert(temp);
                Long tagId = temp.getId();
                strategyCommentMapper.insertRelationStrategyCommentAndTag(strategyCommentId, tagId);
            }
        }
        return strategyCommentId;
    }

    /**
     * 3.根据攻略评论的id查询某一篇攻略评论
     *
     * @param commentId
     * @return
     */
    public StrategyComment getCommentById(Long commentId) {
        return strategyCommentMapper.selectByPrimaryKey(commentId);
    }

    /**
     * 4.查询最近推荐的10条攻略评论,
     * 按照推荐时间倒序
     *
     * @return
     */
    public List<StrategyComment> getTopCommends() {
        return strategyCommentMapper.selectTopComments();
    }

    public void update(StrategyComment strategyComment) {

    }

    public void saveOrUpdate(StrategyComment entity) {
        if (entity.getId() == null) {
            strategyCommentMapper.insert(entity);
        } else {
            strategyCommentMapper.updateByPrimaryKey(entity);
        }
    }

    public List<StrategyComment> list() {
        return strategyCommentMapper.selectAll();
    }


}
